

import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jl_plugin/callback/OpusDecodeCallBack.dart';
import 'package:jl_plugin/jl_plugin.dart';
import 'package:jl_plugin_example/AppBarLeftTitle.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';


class BlueRecordPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _State();
  }

}

class _State extends State<BlueRecordPage> implements OpusDecodeCallBack {
  late JlDeviceCommandCallBack cmdReceive;
  bool isRecord=false;
  bool enableSave=false;
  bool enableLog=false;

  @override
  void initState() {
    super.initState();
    cmdReceive=(int type,String hex,Uint8List bytes){
      print("BlueRecordPage->${hex}");
      var hexList=hex.split(" ");
      if(hexList.isNotEmpty&&hexList.length>2){
        var cmd1=hexList[0];
        var cmd2=hexList[1];
        if("07"==cmd1&&"FF"==cmd2){
          isRecord=hexList[2]=="01";
          setState(() {
            
          });
        }else if("07"==cmd1&&"FE"==cmd2){
          var sublist = bytes.sublist(2,bytes.length);
          var hexs=uint8ListToHex(sublist);
          JlPlugin.instance.decodeOpus(sublist);
          if(enableSave){
            print("lllll:${sublist.length}");
            print("lllll:${hexs}");
            writeOpusData(sublist);
          }

        }
      }
      if(enableLog){
        scrollController.animateTo(
          0,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
        setState(() {
          respList.insert(0,hex);
        });
      }
    };
    JlPlugin.instance.addCommandCmdCallback(cmdReceive);
    JlPlugin.instance.setJlDeviceCommandDecodeCallBack(cmdReceive);
    checkStatus();
    JlPlugin.instance.setOpusDecodeCallBack(this);
  }

  String uint8ListToHex(Uint8List bytes) {
    return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
  }
  ScrollController scrollController=ScrollController();
  List<String> respList=[];
  @override
  void dispose() {
    super.dispose();
    JlPlugin.instance.removeCommandCmdCallback(cmdReceive);
    JlPlugin.instance.releaseDecode();
    JlPlugin.instance.removeOpusDecodeCallBack();
    closeOpusFile();
  }
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarLeftTitle(title: "录音"),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [
          TextButton(onPressed: (){
            checkStatus();
          }, child: Text("获取录音状态"), style: TextButton.styleFrom(
            padding: EdgeInsets.symmetric(horizontal: 5,vertical: 12),          // 去掉内边距
            minimumSize: Size(0, 0),           // 去掉最小尺寸限制
            tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 去掉额外点击区域
            visualDensity: VisualDensity.compact,             // 更紧凑视觉
          ),),
          Row(children: [
            CupertinoSwitch(value: isRecord,onChanged: (value){
              optionRecord(value);
            },),
            Text("录音${isRecord?"已启动":"已停止"}"),
          ],),
          SizedBox(height: 10),
          Row(children: [
            CupertinoSwitch(value: enableSave,onChanged: (value){
              enableSave=value;
              if(value){
                initOpusFile();
              }else{
                closeOpusFile();
              }
              setState(() {

              });
            },),
            Text("opus文件输出${enableSave?"已开启":"已关闭"}"),
            SizedBox(width: 10),


            TextButton(onPressed: (){
              if(enableSave){
                //先停止
                optionRecord(false);
                onDownloadPressed();
              }else{
                closeOpusFile();
              }



            }, child: Text("下载"), style: TextButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 5,vertical: 12),          // 去掉内边距
              minimumSize: Size(0, 0),           // 去掉最小尺寸限制
              tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 去掉额外点击区域
              visualDensity: VisualDensity.compact,             // 更紧凑视觉
            ),),
          ],),
          SizedBox(height: 10),
          Row(children: [
            CupertinoSwitch(value: enableLog,onChanged: (value){
              enableLog=value;
              setState(() {

              });
            },),
            Text("日志输出${enableLog?"已开启":"已关闭"}"),

          ],),
          SizedBox(height: 10),
          Row(children: [
            TextButton(onPressed: (){
              setState(() {
                respList.clear();
              });
            }, child: Text("清空日志"), style: TextButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 5,vertical: 12),          // 去掉内边距
              minimumSize: Size(0, 0),           // 去掉最小尺寸限制
              tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 去掉额外点击区域
              visualDensity: VisualDensity.compact,             // 更紧凑视觉
            ),),
            SizedBox(width: 10),
            TextButton(onPressed: (){
              shareRespList(respList);
            }, child: Text("日志下载"), style: TextButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 5,vertical: 12),          // 去掉内边距
              minimumSize: Size(0, 0),           // 去掉最小尺寸限制
              tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 去掉额外点击区域
              visualDensity: VisualDensity.compact,             // 更紧凑视觉
            ),),
          ],),
          SizedBox(height: 10),
          Expanded(child: ListView.builder(controller: scrollController,itemBuilder: (context,index){
            return Padding(padding: EdgeInsets.only(bottom: 5),child: Text("${respList[index]}"),);
          },itemCount: respList.length,))
        ],),
      ),
    );
  }

  void checkStatus() async{
    JlPlugin.instance.sendCmd("07ff");
  }

  void optionRecord(bool isOpen) async{
    if(isOpen){
      await JlPlugin.instance.startRecord();
      await JlPlugin.instance.startDecode();
    }else{
      await JlPlugin.instance.stopRecord();
      await JlPlugin.instance.stopDecode();
    }
    checkStatus();
  }

  Future<void> shareRespList(List<String> respList) async {
    try {
      // 获取临时目录
      final directory = await getTemporaryDirectory();

      // 拼接内容
      final content = respList.join('\n');

      // 生成文件
      final filePath = '${directory.path}/resp_list.txt';
      final file = File(filePath);
      await file.writeAsString(content);

      // 分享文件
      await Share.shareXFiles(
        [XFile(file.path)],
        text: '这是我导出的内容',
      );
    } catch (e) {
      print("分享失败: $e");
    }
  }


  // 声明变量记录当前opus文件和写入流
  late File opusFile;
  late IOSink opusSink;

// 开启写入时创建文件和写入流
  Future<void> initOpusFile() async {
    final directory = await getApplicationDocumentsDirectory();
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    opusFile = File('${directory.path}/output_$timestamp.opus');
    opusSink = opusFile.openWrite();
    print('OPUS 文件已创建: ${opusFile.path}');
  }

// 写入数据
  void writeOpusData(Uint8List data) {
    if (enableSave) {
      opusSink.add(data);
    }
  }

// 关闭文件流，确保数据写入完整
  Future<void> closeOpusFile() async {
    await opusSink.flush();
    await opusSink.close();
    print('OPUS 文件已完成写入并关闭');
  }

// 下载按钮点击事件，关闭文件写入后分享
  void onDownloadPressed() async {
    if (!enableSave) {
      await closeOpusFile();
    } else {
      enableSave = false;
      setState(() {});
      await closeOpusFile();
    }
    await shareOpusFile();
  }

// 分享文件
  Future<void> shareOpusFile() async {
    if (!opusFile.existsSync()) {
      print("没有可分享的OPUS文件");
      return;
    }
    try {
      await Share.shareXFiles([XFile(opusFile.path)], text: '这是我录制的 OPUS 文件');
    } catch (e) {
      print("分享失败: $e");
    }
  }

  @override
  void onDecodeComplete() {
    print("recode----->onDecodeComplete");
  }

  @override
  void onDecodeError(int code, String message) {
    print("recode----->onDecodeError");
  }

  @override
  void onDecodeStart() {
    print("recode----->onDecodeStart");
  }

  @override
  void onDecodeStream(Uint8List data) {
    print("recode----->onDecodeStream");
  }

}